package com.papercutting.platform.controller;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.util.ImageUrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
@CrossOrigin
public class FileUploadController {

    @Autowired
    private ImageUrlUtil imageUrlUtil;

    @Value("${app.upload.path:/uploads/}")
    private String uploadPath;

    @Value("${app.upload.max-size:10485760}")
    private long maxSize;

    @Value("${app.upload.allowed-types:jpg,jpeg,png,gif}")
    private String allowedTypes;

    @Value("${app.upload.video.max-size:104857600}")
    private long videoMaxSize;

    @Value("${app.upload.video.allowed-types:mp4,avi,mov,wmv,flv,webm}")
    private String videoAllowedTypes;

    /**
     * 上传图片文件
     */
    @PostMapping("/image")
    public Result<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        log.info("上传图片文件: {}", file.getOriginalFilename());
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 检查文件大小
            if (file.getSize() > maxSize) {
                return Result.error("文件大小不能超过 " + (maxSize / 1024 / 1024) + "MB");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }

            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            if (!allowedTypes.contains(extension)) {
                return Result.error("不支持的文件类型，只支持: " + allowedTypes);
            }

            // 创建上传目录
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            // 确保上传目录相对于backend目录
            String baseDir = System.getProperty("user.dir");
            String uploadDir;
            if (baseDir.endsWith("backend")) {
                // 如果当前目录已经是backend，直接使用配置路径
                uploadDir = baseDir + File.separator + uploadPath + datePath;
            } else {
                // 如果当前目录是项目根目录，添加backend前缀
                uploadDir = baseDir + File.separator + "backend" + File.separator + uploadPath + datePath;
            }
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    return Result.error("创建上传目录失败");
                }
            }

            // 生成新文件名
            String newFilename = UUID.randomUUID().toString() + "." + extension;
            String filePath = uploadDir + File.separator + newFilename;
            
            // 保存文件
            File targetFile = new File(filePath);
            file.transferTo(targetFile);

            // 生成访问URL（相对路径）
            String relativeUrl = "/uploads/" + datePath + "/" + newFilename;
            // 生成完整URL
            String fullUrl = imageUrlUtil.getFullServerUrl(relativeUrl);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("filename", newFilename);
            result.put("originalFilename", originalFilename);
            result.put("url", fullUrl);
            result.put("size", file.getSize());
            result.put("type", extension);

            log.info("文件上传成功: {}", fullUrl);
            return Result.success("文件上传成功", result);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传头像
     */
    @PostMapping("/avatar")
    public Result<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        log.info("上传头像: {}", file.getOriginalFilename());
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 检查文件大小（头像限制为2MB）
            long avatarMaxSize = 2 * 1024 * 1024; // 2MB
            if (file.getSize() > avatarMaxSize) {
                return Result.error("头像大小不能超过 2MB");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }

            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            if (!allowedTypes.contains(extension)) {
                return Result.error("不支持的文件类型，只支持: " + allowedTypes);
            }

            // 创建头像目录（固定目录，不按日期分）
            String baseDir = System.getProperty("user.dir");
            String uploadDir;
            if (baseDir.endsWith("backend")) {
                uploadDir = baseDir + File.separator + uploadPath + "images" + File.separator + "avatar";
            } else {
                uploadDir = baseDir + File.separator + "backend" + File.separator + uploadPath + "images" + File.separator + "avatar";
            }
            
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                if (!created) {
                    return Result.error("创建上传目录失败");
                }
            }

            // 生成新文件名
            String newFilename = UUID.randomUUID().toString() + "." + extension;
            String filePath = uploadDir + File.separator + newFilename;
            
            // 保存文件
            File targetFile = new File(filePath);
            file.transferTo(targetFile);

            // 生成访问URL（相对路径）
            String relativeUrl = "/images/avatar/" + newFilename;
            // 生成完整URL
            String fullUrl = imageUrlUtil.getFullServerUrl(relativeUrl);
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("filename", newFilename);
            result.put("originalFilename", originalFilename);
            result.put("url", fullUrl);
            result.put("size", file.getSize());
            result.put("type", extension);

            log.info("头像上传成功: {}", fullUrl);
            return Result.success("头像上传成功", result);

        } catch (IOException e) {
            log.error("头像上传失败", e);
            return Result.error("头像上传失败: " + e.getMessage());
        }
    }

    /**
     * 上传视频文件
     */
    @PostMapping("/video")
    public Result<Map<String, Object>> uploadVideo(@RequestParam("file") MultipartFile file) {
        log.info("上传视频文件: {}", file.getOriginalFilename());
        log.info("配置的上传路径: {}", uploadPath);

        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 检查文件大小
            if (file.getSize() > videoMaxSize) {
                return Result.error("视频文件大小不能超过 " + (videoMaxSize / 1024 / 1024) + "MB");
            }

            // 获取文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                return Result.error("文件名不能为空");
            }

            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();

            // 检查文件类型
            String[] allowedVideoTypes = videoAllowedTypes.split(",");
            boolean isAllowedType = false;
            for (String type : allowedVideoTypes) {
                if (type.trim().equals(extension)) {
                    isAllowedType = true;
                    break;
                }
            }

            if (!isAllowedType) {
                return Result.error("不支持的视频格式，支持的格式：" + videoAllowedTypes);
            }

            // 创建上传目录
            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
            
            // 确保上传目录相对于backend目录
            String baseDir = System.getProperty("user.dir");
            String uploadDir;
            if (baseDir.endsWith("backend")) {
                // 如果当前目录已经是backend，直接使用配置路径
                uploadDir = baseDir + File.separator + uploadPath + datePath;
            } else {
                // 如果当前目录是项目根目录，添加backend前缀
                uploadDir = baseDir + File.separator + "backend" + File.separator + uploadPath + datePath;
            }
            log.info("基础目录: {}", baseDir);
            log.info("完整上传目录路径: {}", uploadDir);

            File dir = new File(uploadDir);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                log.info("目录创建结果: {}, 路径: {}", created, dir.getAbsolutePath());
            }

            // 生成新文件名
            String newFilename = UUID.randomUUID().toString() + "." + extension;
            String filePath = uploadDir + File.separator + newFilename;

            // 保存文件
            File targetFile = new File(filePath);
            log.info("目标文件路径: {}", targetFile.getAbsolutePath());

            // 使用字节流方式保存文件，避免transferTo的路径问题
            try (InputStream inputStream = file.getInputStream();
                 FileOutputStream outputStream = new FileOutputStream(targetFile)) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            }

            // 生成访问URL（相对路径）
            String relativeUrl = "/uploads/" + datePath + "/" + newFilename;
            // 生成完整URL
            String fullUrl = imageUrlUtil.getFullServerUrl(relativeUrl);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("filename", newFilename);
            result.put("originalFilename", originalFilename);
            result.put("url", fullUrl);
            result.put("size", file.getSize());
            result.put("type", extension);

            log.info("视频文件上传成功: {}", fullUrl);
            return Result.success("视频文件上传成功", result);

        } catch (IOException e) {
            log.error("视频文件上传失败", e);
            return Result.error("视频文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/image")
    public Result<Void> deleteImage(@RequestParam("url") String fileUrl) {
        log.info("删除文件: {}", fileUrl);
        
        try {
            if (fileUrl == null || fileUrl.isEmpty()) {
                return Result.error("文件URL不能为空");
            }

            // 构造文件路径
            String baseDir = System.getProperty("user.dir");
            String filePath;
            if (baseDir.endsWith("backend")) {
                filePath = baseDir + fileUrl;
            } else {
                filePath = baseDir + File.separator + "backend" + fileUrl;
            }
            File file = new File(filePath);
            
            if (file.exists() && file.isFile()) {
                boolean deleted = file.delete();
                if (deleted) {
                    log.info("文件删除成功: {}", fileUrl);
                    return Result.success("文件删除成功");
                } else {
                    return Result.error("文件删除失败");
                }
            } else {
                return Result.error("文件不存在");
            }
            
        } catch (Exception e) {
            log.error("文件删除失败", e);
            return Result.error("文件删除失败: " + e.getMessage());
        }
    }

    /**
     * 删除视频文件
     */
    @DeleteMapping("/video")
    public Result<Void> deleteVideo(@RequestParam("url") String fileUrl) {
        log.info("删除视频文件: {}", fileUrl);

        try {
            if (fileUrl == null || fileUrl.isEmpty()) {
                return Result.error("文件URL不能为空");
            }

            // 构建文件路径
            String baseDir = System.getProperty("user.dir");
            String relativePath = fileUrl.replace("/uploads/", "");
            String filePath;
            if (baseDir.endsWith("backend")) {
                filePath = baseDir + File.separator + uploadPath + relativePath;
            } else {
                filePath = baseDir + File.separator + "backend" + File.separator + uploadPath + relativePath;
            }
            File file = new File(filePath);

            if (file.exists() && file.isFile()) {
                boolean deleted = file.delete();
                if (deleted) {
                    log.info("视频文件删除成功: {}", fileUrl);
                    return Result.success("视频文件删除成功");
                } else {
                    return Result.error("视频文件删除失败");
                }
            } else {
                return Result.error("视频文件不存在");
            }

        } catch (Exception e) {
            log.error("视频文件删除失败", e);
            return Result.error("视频文件删除失败: " + e.getMessage());
        }
    }
}